<template>
  <div class="order-page">
    <div class="container">
      <div class="main">
        <div class="order-header">
          <h2>我的订单</h2>
          <!-- 订单状态筛选 -->
          <div class="filter-tabs">
            <el-tabs v-model="activeTab" @tab-change="handleTabChange">
              <el-tab-pane label="全部订单" name="all"></el-tab-pane>
              <el-tab-pane label="待付款" name="1"></el-tab-pane>
              <el-tab-pane label="待发货" name="2"></el-tab-pane>
              <el-tab-pane label="待收货" name="3"></el-tab-pane>
              <el-tab-pane label="待评价" name="4"></el-tab-pane>
              <el-tab-pane label="已完成" name="5"></el-tab-pane>
              <el-tab-pane label="已取消" name="6"></el-tab-pane>
            </el-tabs>
          </div>
        </div>

        <!-- 订单列表 -->
        <div class="order-list" v-if="orders.length > 0">
          <div class="order-item" v-for="order in orders" :key="order.orderInfo?.id || order.id">
            <div class="order-info">
              <div class="order-head">
                <span>订单号：{{ order.orderInfo?.orderno || order.orderno || order.id }}</span>
                <span class="order-status" :class="`status-${order.orderInfo?.orderstate || order.orderstate}`">
                  {{ getOrderStatusText(order.orderInfo?.orderstate || order.orderstate) }}
                </span>
              </div>
              <!-- 添加购买人和收货地址信息 -->
              <div class="order-address">
                <p>购买人：{{ order.orderInfo?.receivercontact || order.receivercontact }}</p>
                <p>联系方式：{{ order.orderInfo?.receivermobile || order.receivermobile }}</p>
                <p>收货地址：{{ order.orderInfo?.receiveraddress || order.receiveraddress }}</p>
                <!-- 添加修改地址按钮 -->
                <el-button 
                  v-if="(order.orderInfo?.orderstate || order.orderstate) == 1"
                  size="small" 
                  @click="openEditAddress(order)"
                  class="edit-address-btn"
                >
                  修改地址
                </el-button>
              </div>
              <div class="order-goods">
                <!-- 显示订单中的商品信息 -->
                <div class="goods-item" v-for="goods in order.orderItemList" :key="goods.id">
                  <div class="goods-pic">
                    <img :src="goods.image" :alt="goods.name" />
                  </div>
                  <div class="goods-info">
                    <div class="goods-name">{{ goods.productName || goods.name }}</div>
                    <div class="goods-specs">{{ goods.attrstext }}</div>
                    <div class="goods-price">¥{{ goods.realpay }}</div>
                  </div>
                  <div class="goods-count">x{{ goods.quantity }}</div>
                </div>
              </div>
              <div class="order-total">
                <span>共{{ order.orderInfo?.totalnum || order.totalnum }}件商品，合计：</span>
                <span class="total-price">¥{{ (order.orderInfo?.paymoney || order.paymoney)?.toFixed(2) }}</span>
              </div>
              <div class="order-actions">
                <el-button 
                  v-if="(order.orderInfo?.orderstate || order.orderstate) == 1"
                  type="primary" 
                  @click="handlePay(order)"
                >
                  立即支付
                </el-button>
                <el-button 
                  v-if="(order.orderInfo?.orderstate || order.orderstate) == 3"
                  @click="handleConfirm(order)"
                >
                  确认收货
                </el-button>
                <el-button 
                  v-if="(order.orderInfo?.orderstate || order.orderstate) == 4"
                  type="primary" 
                  @click="handleComment(order)"
                >
                  去评价
                </el-button>
                <el-button 
                  @click="handleDeleteOrder(order)"
                  :loading="deletingOrderId === (order.orderInfo?.id || order.id)"
                >
                  删除订单
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div class="order-empty" v-else>
          <el-empty description="暂无订单">
            <el-button type="primary" @click="$router.push('/')">去逛逛</el-button>
          </el-empty>
        </div>
      </div>
    </div>

    <!-- 修改地址弹窗 -->
    <el-dialog v-model="addressEditVisible" title="修改收货地址" width="500px" :before-close="handleClose">
      <div class="address-selection">
        <div class="address-list">
          <div 
            class="address-item" 
            :class="{ active: selectedAddress.aid === item.aid }"
            v-for="item in addressList" 
            :key="item.aid"
            @click="selectAddress(item)"
          >
            <ul>
              <li><span>收<i />货<i />人：</span>{{ item.contactor }}</li>
              <li><span>联系方式：</span>{{ item.phone }}</li>
              <li><span>收货地址：</span>{{ item.address }}</li>
            </ul>
            <div class="address-actions">
              <el-button type="primary" link @click.stop="editExistingAddress(item)">编辑</el-button>
              <el-button type="danger" link @click.stop="handleDeleteAddress(item.aid)">删除</el-button>
            </div>
          </div>
          <div class="address-item add-new" @click="addNewAddress">
            <div class="add-icon">+</div>
            <div>添加新地址</div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addressEditVisible = false">取消</el-button>
          <el-button type="primary" @click="saveSelectedAddress">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加/编辑地址表单 -->
    <el-dialog 
      v-model="addressFormVisible" 
      :title="editingAddress.aid ? '编辑收货地址' : '添加收货地址'"
      width="500px"
    >
      <el-form :model="addressForm" label-width="80px" ref="addressFormRef">
        <el-form-item label="收货人">
          <el-input v-model="addressForm.contactor" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="addressForm.phone" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="收货地址">
          <el-input 
            v-model="addressForm.address"
            type="textarea" 
            :rows="3" 
            placeholder="请输入详细收货地址">
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addressFormVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAddressForm">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrderListAPI, deleteOrderAPI, updateOrderStateAPI, getOrderDetailAPI, updateOrderAddressAPI } from '@/apis/order'
import { getAddressList, addAddress, updateAddress, deleteAddress } from '@/apis/address'
import { getProductDetail } from '@/apis/product'

const activeTab = ref('all')
const orders = ref([])
const allOrders = ref([])
const deletingOrderId = ref(null)
const router = useRouter()

// 修改地址相关
const addressEditVisible = ref(false)
const addressFormVisible = ref(false)
const addressList = ref([])
const selectedAddress = ref({})
const currentEditOrder = ref(null)
const addressForm = ref({
  contactor: '',
  phone: '',
  address: ''
})
const addressFormRef = ref(null)
const editingAddress = ref({})

// 获取订单状态文本
const getOrderStatusText = (status) => {
  const statusMap = {
    1: '待付款',
    2: '待发货',
    3: '待收货',
    4: '待评价',
    5: '已完成',
    6: '已取消'
  }
  return statusMap[status] || '未知状态'
}

// 获取订单列表
const getOrders = async () => {
  try {
    // 使用实际API获取订单数据
    const res = await getOrderListAPI()
    if (res.code === 200) {
      // 获取每个订单的详细信息
      const orderPromises = res.data.map(async (order) => {
        try {
          const detailRes = await getOrderDetailAPI(order.id)
          if (detailRes.code === 200) {
            // 获取订单中每个商品的详细信息
            const orderItemList = await Promise.all(
              detailRes.data.orderItemList.map(async (item) => {
                try {
                  // 通过PID获取商品信息
                  console.log('item', item)
                  const productRes = await getProductDetail(item.spuid)
                  console.log('商品信息:', productRes)
                  if (productRes.code === 200) {
                    return {
                      ...item,
                      productName: productRes.data.pname
                    }
                  } else {
                    return item
                  }
                } catch (error) {
                  console.error(`获取商品信息失败:`, error)
                  return item
                }
              })
            )
            
            return {
              orderInfo: order,
              ...detailRes.data,
              orderItemList: orderItemList
            }
          } else {
            // 如果获取详情失败，返回原始订单信息
            return {
              orderInfo: order
            }
          }
        } catch (error) {
          console.error(`获取订单${order.id}详情失败:`, error)
          // 如果获取详情失败，返回原始订单信息
          return {
            orderInfo: order
          }
        }
      })
      
      // 等待所有订单详情获取完成
      allOrders.value = await Promise.all(orderPromises)
      filterOrders()
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  }
}

// 根据标签页筛选订单
const filterOrders = () => {
  if (activeTab.value === 'all') {
    orders.value = allOrders.value
  } else {
    orders.value = allOrders.value.filter(order => 
      (order.orderInfo?.orderstate || order.orderstate) == activeTab.value)
  }
}

// 标签页切换
const handleTabChange = () => {
  filterOrders()
}

// 打开修改地址弹窗
const openEditAddress = async (order) => {
  currentEditOrder.value = order
  addressEditVisible.value = true
  
  // 获取地址列表
  try {
    const res = await getAddressList()
    addressList.value = res.data || []
    
    // 设置当前地址为选中状态
    if (addressList.value.length > 0) {
      // 查找与当前订单地址匹配的地址
      const currentOrderAddress = {
        contactor: order.orderInfo?.receivercontact || order.receivercontact,
        phone: order.orderInfo?.receivermobile || order.receivermobile,
        address: order.orderInfo?.receiveraddress || order.receiveraddress
      }
      
      const matchedAddress = addressList.value.find(addr => 
        addr.contactor === currentOrderAddress.contactor &&
        addr.phone === currentOrderAddress.phone &&
        addr.address === currentOrderAddress.address
      )
      
      if (matchedAddress) {
        selectedAddress.value = matchedAddress
      } else {
        selectedAddress.value = {}
      }
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
    ElMessage.error('获取地址列表失败')
  }
}

// 选择地址
const selectAddress = (address) => {
  selectedAddress.value = address
}

// 编辑现有地址
const editExistingAddress = (address) => {
  editingAddress.value = address
  addressForm.value = { ...address }
  addressFormVisible.value = true
}

// 添加新地址
const addNewAddress = () => {
  editingAddress.value = {}
  addressForm.value = {
    contactor: '',
    phone: '',
    address: ''
  }
  addressFormVisible.value = true
}

// 保存地址表单
const saveAddressForm = async () => {
  try {
    // 表单验证
    if (!addressForm.value.contactor) {
      ElMessage.warning('请输入收货人姓名')
      return
    }
    if (!addressForm.value.phone) {
      ElMessage.warning('请输入联系方式')
      return
    }
    if (!addressForm.value.address) {
      ElMessage.warning('请输入收货地址')
      return
    }

    if (editingAddress.value.aid) {
      // 更新地址
      await updateAddress(addressForm.value)
      ElMessage.success('地址更新成功')
    } else {
      // 添加地址
      await addAddress(addressForm.value)
      ElMessage.success('地址添加成功')
    }
    
    addressFormVisible.value = false
    // 重新加载地址列表
    openEditAddress(currentEditOrder.value)
  } catch (error) {
    ElMessage.error((editingAddress.value.aid ? '地址更新失败' : '地址添加失败') + ': ' + (error.message || '未知错误'))
  }
}

// 删除地址
const removeAddress = async (aid) => {
  try {
    await deleteAddress(aid)
    ElMessage.success('地址删除成功')
    // 重新加载地址列表
    openEditAddress(currentEditOrder.value)
  } catch (error) {
    ElMessage.error('地址删除失败: ' + (error.message || '未知错误'))
  }
}

// 删除地址的确认对话框
const handleDeleteAddress = (aid) => {
  ElMessageBox.confirm(
    '确定要删除该收货地址吗？',
    '提示',
    {
      type: 'warning'
    }
  ).then(() => {
    removeAddress(aid)
  }).catch(() => {
    // 用户取消删除
  })
}

// 保存选中的地址
const saveSelectedAddress = async () => {
  if (!selectedAddress.value.aid) {
    ElMessage.warning('请选择一个地址')
    return
  }
  
  try {
    // 调用新添加的更新订单地址API
    const orderId = currentEditOrder.value.orderInfo?.id || currentEditOrder.value.id
    const res = await updateOrderAddressAPI(orderId, selectedAddress.value.aid)
    
    if (res.code === 200) {
      // 更新本地数据
      if (currentEditOrder.value.orderInfo) {
        currentEditOrder.value.orderInfo.receivercontact = selectedAddress.value.contactor
        currentEditOrder.value.orderInfo.receivermobile = selectedAddress.value.phone
        currentEditOrder.value.orderInfo.receiveraddress = selectedAddress.value.address
      } else {
        currentEditOrder.value.receivercontact = selectedAddress.value.contactor
        currentEditOrder.value.receivermobile = selectedAddress.value.phone
        currentEditOrder.value.receiveraddress = selectedAddress.value.address
      }
      
      addressEditVisible.value = false
      ElMessage.success('地址修改成功')
    } else {
      ElMessage.error(res.msg || '地址修改失败')
    }
  } catch (error) {
    console.error('保存地址失败:', error)
    ElMessage.error('保存地址失败: ' + (error.message || '未知错误'))
  }
}

// 关闭弹窗前的确认
const handleClose = (done) => {
  ElMessageBox.confirm('确认关闭？修改的内容将不会保存')
    .then(() => {
      done()
    })
    .catch(() => {
      // 取消关闭
    })
}

// 立即支付
const handlePay = (order) => {
  router.push({
    path: '/pay',
    query: {
      id: order.orderInfo?.id || order.id
    }
  })
}

// 确认收货
const handleConfirm = async (order) => {
  ElMessageBox.confirm(
    '确认收货后，订单状态将变更为待评价，是否确认收货？',
    '确认收货',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      // 调用API更新订单状态
      const orderId = order.orderInfo?.id || order.id
      const res = await updateOrderStateAPI(orderId, 4)
      if (res.code === 200) {
        if (order.orderInfo) {
          order.orderInfo.orderstate = 4
        } else {
          order.orderstate = 4
        }
        ElMessage.success('确认收货成功')
      } else {
        ElMessage.error(res.msg || '确认收货失败')
      }
    } catch (error) {
      console.error('确认收货失败:', error)
      ElMessage.error('确认收货失败')
    }
  })
}

// 去评价
const handleComment = (order) => {
  ElMessageBox.alert('评价功能暂未实现', '提示', {
    confirmButtonText: '确定'
  })
}

// 删除订单
const handleDeleteOrder = (order) => {
  const orderId = order.orderInfo?.id || order.id
  ElMessageBox.confirm(
    '确定要删除该订单吗？删除后无法恢复',
    '删除订单',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    deletingOrderId.value = orderId
    try {
      // 调用API删除订单
      const res = await deleteOrderAPI(orderId)
      if (res.code === 200) {
        const index = orders.value.findIndex(item => 
          (item.orderInfo?.id || item.id) === orderId)
        if (index > -1) {
          orders.value.splice(index, 1)
        }
        
        const allIndex = allOrders.value.findIndex(item => 
          (item.orderInfo?.id || item.id) === orderId)
        if (allIndex > -1) {
          allOrders.value.splice(allIndex, 1)
        }
        
        ElMessage.success('删除成功')
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除订单失败:', error)
      ElMessage.error('删除失败')
    } finally {
      deletingOrderId.value = null
    }
  })
}

onMounted(() => {
  getOrders()
})
</script>

<style scoped lang="scss">
.order-page {
  background-color: #f5f5f5;
  min-height: 600px;
  padding: 20px 0;

  .main {
    background: #fff;
    padding: 20px;
  }

  .order-header {
    h2 {
      font-size: 20px;
      margin-bottom: 20px;
    }
  }

  .filter-tabs {
    margin-bottom: 20px;

    :deep(.el-tabs__header) {
      margin-bottom: 0;
    }
  }

  .order-item {
    border: 1px solid #e4e4e4;
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .order-info {
    padding: 20px;
  }

  .order-head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 10px;
    border-bottom: 1px solid #e4e4e4;
    margin-bottom: 20px;
    font-size: 14px;
    color: #999;

    .order-status {
      color: $priceColor;
      font-weight: bold;

      &.status-1 {
        color: #e26237;
      }

      &.status-2 {
        color: #334455;
      }

      &.status-3 {
        color: #1dc779;
      }

      &.status-4 {
        color: #ff9900;
      }

      &.status-5 {
        color: #666;
      }

      &.status-6 {
        color: #999;
      }
    }
  }

  /* 添加订单地址信息样式 */
  .order-address {
    padding: 10px;
    background-color: #f8f8f8;
    border-radius: 4px;
    margin-bottom: 15px;
    font-size: 14px;
    position: relative;
    
    p {
      margin: 5px 0;
      color: #666;
    }
    
    .edit-address-btn {
      position: absolute;
      right: 10px;
      top: 50%;
      transform: translateY(-50%);
    }
  }

  .order-goods {
    margin-bottom: 20px;
  }

  .goods-item {
    display: flex;
    align-items: center;
    padding: 10px 0;

    &:not(:last-child) {
      border-bottom: 1px solid #e4e4e4;
    }
  }

  .goods-pic {
    width: 100px;
    height: 100px;
    border: 1px solid #e4e4e4;
    margin-right: 10px;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .goods-info {
    flex: 1;
    padding-right: 10px;
  }

  .goods-name {
    font-size: 14px;
    color: #333;
    margin-bottom: 5px;
  }

  .goods-specs {
    font-size: 12px;
    color: #999;
    margin-bottom: 10px;
  }

  .goods-price {
    font-size: 14px;
    color: $priceColor;
  }

  .goods-count {
    font-size: 14px;
    color: #333;
  }

  .order-total {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 10px 0;
    border-top: 1px solid #e4e4e4;
    font-size: 14px;
    color: #333;

    .total-price {
      font-size: 16px;
      color: $priceColor;
      margin-left: 5px;
    }
  }

  .order-actions {
    display: flex;
    justify-content: flex-end;
    padding-top: 10px;
    border-top: 1px solid #e4e4e4;

    .el-button {
      margin-left: 10px;
    }
  }

  .order-empty {
    padding: 100px 0;
    text-align: center;
  }
}

// 地址选择样式
.address-selection {
  .address-list {
    max-height: 400px;
    overflow-y: auto;
  }
  
  .address-item {
    border: 1px solid #e4e4e4;
    padding: 15px;
    margin-bottom: 10px;
    cursor: pointer;
    position: relative;
    
    &.active {
      border-color: $xtxColor;
      background-color: #f6f6f6;
    }
    
    &:hover {
      background-color: #f9f9f9;
    }
    
    ul {
      li {
        margin-bottom: 5px;
        font-size: 14px;
        
        span {
          color: #999;
          display: inline-block;
          width: 70px;
        }
      }
    }
    
    .address-actions {
      position: absolute;
      top: 15px;
      right: 15px;
    }
  }
  
  .add-new {
    text-align: center;
    padding: 30px 0;
    color: #999;
    border-style: dashed;
    
    .add-icon {
      font-size: 24px;
      font-weight: bold;
    }
  }
}
</style>